package com.sj.security;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.sj.entity.SysMenu;
import com.sj.entity.User;
import com.sj.service.SysMenuService;
import com.sj.service.UserService;
import com.sj.utils.JwtUtils;
import com.sj.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-10
 * Time: 下午 12:31
 * Description: 登录成功处理器
 *
 * @author xiaoqi
 * @since 2022-03-10
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${know.tokenKey}")
    private String userTokenKey;

    @Autowired
    private UserService userService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置返回数据类型
        response.setContentType("application/json;charset=UTF-8");
        SecurityUser securityUser = null;
        if (authentication.getPrincipal() instanceof SecurityUser) {
            securityUser = (SecurityUser) authentication.getPrincipal();
        }
        MapBuilder<Object, Object> builder = MapUtil.builder();
        if (securityUser == null) {
            builder.put("code", HttpServletResponse.SC_BAD_REQUEST)
                    .put("msg", "用户信息错误")
                    .put("data", null);
        } else {
            String token = jwtUtils.generateToken(securityUser.getId() + "-" + securityUser.getUsername());
            User user = userService.getById(securityUser.getId());
            String authorities = userService.getAuthorities(user.getId(), user.getUsername());
            user.setPassword(null);
            builder.put("code", HttpServletResponse.SC_OK)
                    .put("msg", "登录成功")
                    .put("data", MapUtil.builder()
                            .put("token", token)
                            .put("user", user)
                            .put("auth", authorities)
                            .build());
            redisUtils.set(userTokenKey + "-" + securityUser.getUsername(), token, jwtUtils.getExpire());
        }
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(builder.build()).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}